package com.baidu.ocrgeneralocrdemo;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import static android.Manifest.permission.CAMERA;
import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
import static android.content.pm.PackageManager.PERMISSION_GRANTED;

import com.alibaba.fastjson.JSON;
import com.baidu.ocrgeneralocrdemo.model.OCRModel;
import com.baidu.ocrgeneralocrdemo.model.OCRResponseModel;
import com.mengpeng.mphelper.ToastUtils;
import com.zhouyou.http.EasyHttp;
import com.zhouyou.http.callback.CallBack;
import com.zhouyou.http.exception.ApiException;

import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.RequestBody;

public class MainActivity extends AppCompatActivity {
    private TextView qualityCheckResultView = null;
    private Context mContext;
    private Activity mActivity;
    public static final String KEY_IMAGE_PATH = "imagePath";
    Uri cropImageUri;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        qualityCheckResultView = findViewById(R.id.quality_check_result);

        mContext = this;
        mActivity = this;

        getPermission();

        initModel();
        init();
    }

    void getPermission() {
        if (ContextCompat.checkSelfPermission(this, CAMERA) != PERMISSION_GRANTED ||
                ContextCompat.checkSelfPermission(this, WRITE_EXTERNAL_STORAGE) != PERMISSION_GRANTED ||
                ContextCompat.checkSelfPermission(this, READ_EXTERNAL_STORAGE) != PERMISSION_GRANTED) {

            ActivityCompat.requestPermissions(this,
                    new String[]{CAMERA, READ_EXTERNAL_STORAGE, WRITE_EXTERNAL_STORAGE}, 1);
        }
    }


   void initModel(){
        // 初始化模板
       Thread thread = new Thread(new Runnable() {
           public void run() {
               // 授权初始化
               if (!PredictorWrapper.initLicense(mActivity, qualityCheckResultView)) {
                   return;
               }
               // 初始化模型
               PredictorWrapper.initModel(mActivity, qualityCheckResultView, new PredictorResultListener() {
                   @Override
                   public void ResultListener(String result) throws IOException {
                       ToastUtils.onShowToast(result);
                   }
               });
           }
       });
       thread.start();

   }



    public void init() {
//        Button fab = findViewById(R.id.bt_init);
//        fab.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                Thread thread = new Thread(new Runnable() {
//                    public void run() {
//                        // 授权初始化
//                        if (!PredictorWrapper.initLicense(mActivity, qualityCheckResultView)) {
//                            return;
//                        }
//                        // 初始化模型
//                        PredictorWrapper.initModel(mActivity, qualityCheckResultView, new PredictorResultListener() {
//                            @Override
//                            public void ResultListener(String result) throws IOException {
//                                ToastUtils.onDefaultShowToast(result);
//                            }
//                        });
//                    }
//                });
//                thread.start();
//            }
//        });

        // Button关联图片测试activity
        Button button = findViewById(R.id.bt_test_photo_image);
        button.setOnClickListener(new Button.OnClickListener() {
            @Override
            public void onClick(View view) {
//                Intent intent = new Intent(mContext, CustomCameraActivity.class);
//                startActivity(intent);
                gotoCamare();
            }
        });

        // Button 关联摄像头视频流测试activity
//        button = findViewById(R.id.bt_test_camera_stream);
//        button.setOnClickListener(new Button.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                Intent intent = new Intent(mContext, TestCameraStreamActivity.class);
//                startActivity(intent);
//            }
//        });

        // Button 关联摄像头拍摄图片测试activity
//        button = findViewById(R.id.bt_test_camera_image);
//        button.setOnClickListener(new Button.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                Intent intent = new Intent(mContext, TestCameraImageActivity.class);
//                startActivity(intent);
//            }
//        });
//
//        // Button 关联assets图片测试activity
//        button = findViewById(R.id.bt_test_assets_image);
//        button.setOnClickListener(new Button.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                Intent intent = new Intent(mContext, TestAssetsImageActivity.class);
//                startActivity(intent);
//            }
//        });

    }

    public void gotoCamare() {
        CameraActivity.startMe(this, 2005, CameraActivity.MongolianLayerType.BANK_CARD);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            cropImageUri = Uri.fromFile(new File(data.getStringExtra(KEY_IMAGE_PATH)));

//            resultImg.setImageURI(cropImageUri);
//            uploadBtn.setVisibility(View.VISIBLE);
            gotoUpLoad();
        }
    }

    public void gotoUpLoad() {


        Bitmap bitmap = null;
        try {
            bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(cropImageUri));
            PredictorWrapper.asyncTestOneImage(this, bitmap, null, null, new PredictorResultListener() {
                @Override
                public void ResultListener(String result) throws IOException {
                    postResultToService(result);
                    //  Context context;
                    // ToastUtil.showToast(context,result);
                }
            });
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

//        CameraActivity.startMe(this, 2005, CameraActivity.MongolianLayerType.BANK_CARD);
    }

    public  void postResultToService(String result) throws IOException {


        final MediaType contentType = MediaType.parse("application/json; charset=utf-8");
        Map<String, String> map = new HashMap<String, String>();
        map.put("parameter",result);
        JSONObject jsonObject = new JSONObject(map);
        RequestBody requestBody = RequestBody.create(contentType, jsonObject.toString());
        EasyHttp.post("/orc/parsingInformation")
                .baseUrl("http://192.168.0.115:8999")
                .requestBody(requestBody)
                .execute(new CallBack<String>() {
                    @Override
                    public void onStart() {

                    }

                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onSuccess(String s) {
                        OCRResponseModel responseModelmodel  = JSON.parseObject(s,OCRResponseModel.class);
                        if(responseModelmodel.getCode() == 0){
                            OCRModel model = responseModelmodel.getData();
                            ToastUtils.onSuccessShowToast(model.getName()+"\n"+model.getPhone()+"\n"+model.getAddress());
                                ReplayOnCarmea();
                        }else {
                            ToastUtils.onErrorShowToast("上传失败");
                        }

                    }

                    @Override
                    public void onError(ApiException e) {
                        ToastUtils.onErrorShowToast(e.getMessage());
                    }
                });


    }
      void ReplayOnCarmea() {
        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                gotoCamare();
            }
        });
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        // noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

